use crate::config::get;
use crate::error::LoginError::UserOrPassword;
use crate::mapper::*;
use crate::redis::*;
use crate::token::Token;
use crate::token::JWT;

/// 用户登录
pub async fn login(user_name: &str, password: &str) -> anyhow::Result<Token> {
    tracing::info!("login user: {}:{}", user_name, password);

    let user = query_user_from_username(user_name).await?;

    match &user {
        Some(u) => {
            if u.password != password {
                return Err(anyhow::anyhow!(UserOrPassword))
            }
        },
        None => return Err(anyhow::anyhow!(UserOrPassword))
    }

    let token_string = JWT::new(String::from(user_name), String::from(user_name) ).generate()?;
    let token_info = Token::new(user_name, &token_string);

    // 记录当前token
    let name = get().token()?.name();
    let expire = get().token()?.timeout();
    set_string_expire(&format!("{}:{}", name, user_name), &token_info.to_string(), expire).await?;
    set_string_expire(&token_string, &user.unwrap().code, expire).await?;

    Ok(token_info)
}